<template>
    <view class="wrapper" :class="{'bg': !is_into}">
      <scan />
      <view class="header">
        <view class="title">包发财仓库管理</view>
        <view class="ops" :class="{'color' : is_into}">[ {{ is_into ? '入库操作' : '出库操作' }} ]</view>
		<view v-if="driverUser">
			<button @click="logout" style="margin-top: 20rpx;margin-left: 20rpx;color: #fff;background-color: red;">退出登录</button>
		</view>
      </view>
      <view class="menu">
        <view class="into" @click="into">
          <image src="/static/into.png" mode="widthFix" />
          <text>入库扫描</text>
        </view>
        <view class="out" @click="out">
          <image src="/static/out.png" mode="widthFix" />
          <text>出库扫描</text>
        </view>
      </view>
      <view class="main">
        <view class="success" v-if="success_text.length > 0">{{success_text}}</view>
        <view class="sn" v-if="scanOder.order_sn">订单号: {{scanOder.order_sn}}</view>
        <view class="sn" v-if="+order.total > 0">总数量: {{order.total}}</view>
        <block v-if="order.list && order.list.length > 0 && +allStatus === 1">
          <view>商品详情:</view>
          <view class="item" v-for="(item, index) in order.list">
            {{item.name}} x {{item.quantity}}
          </view>
          <view style="background: none"></view>
        </block>
		
		
		<block v-if="order.return_goods && order.return_goods.length > 0 && +allStatus === 1">
		  <view>退货商品详情:</view>
		  <view class="item" v-for="(item, index) in order.return_goods">
		    {{item.name}} x {{item.goods_num}}
		  </view>
		  <view style="background: none"></view>
		</block>
      </view>
    </view>
</template>

<script>
/**
 * 1) 需要 打开PDA广播
 * 2) 设置2个参数
 */
import Scan from "@/components/scan/scan.vue";
import Request from "../../util/Request";
const request = new Request();

export default {
  components: {
    Scan
  },
  data() {
    return {
      // is into or out
      is_into: true,
      // success_text: '扫描成功...',
      success_text: '',
      /**
       * api get
       **/
      order: {
        // sn: '12131231231231231',
        // total: 3,
        // list: [
        //   {name: '这是一个测试商品', quantity: 1}
        // ]
      },
      /**
       * scan code
       * {"order_id":14,"order_sn":"2022022222165373913"}
       */
      scanOder: {},
      allStatus: 0,
      mp3Src: '/static/mp3/test.mp3',
      innerAudio: null,
	  driverUser:''
    }
  },
  methods: {
    pay(src = false) {
      if (!src) {
        src = this.mp3Src
      }
      this.innerAudio.stop()
      this.innerAudio.src = src
      this.innerAudio.play()
      this.innerAudio.onEnded(() => {
        console.log('自然播放完成')
      })
    },
    // stop() {
    //   this.innerAudio.stop()
    // },
    into() {
      this.is_into = true
      this.success_text = ''
      this.order = {}
      this.allStatus = 0
      // this.pay()
    },
    out() {
      this.is_into = false
      this.success_text = ''
      this.order = {}
      this.allStatus = 0
	 
	  if (!this.driverUser) {
		  uni.redirectTo({
		  	url:'/pages/login/login'
		  })
	  }
    },
    submit() {
      // console.log(this.scanOder)
	  let _this = this;
      if (this.is_into) {
        // this.into()
		request.into({..._this.scanOder}).then(response => {
		 
		  const { data } = response
		  if (data.type==1) {
			   _this.pay('/static/music/success.mp3')
		  }else{
			   _this.pay('/static/mp3/into_success_return_goods.mp3')
		  }
		  _this.order = (data.order && data.order) || {}
		  _this.success_text = data.message || ''
		  _this.allStatus = data.status || 0
		  uni.showToast({
		    title: _this.success_text,
		    duration: 800,
		    icon: 'none',
		  })
		}).catch(err => {
		  if (err.message) {
			  if (err.message=='订单已经被取消') {
				  _this.pay('/static/mp3/into_order_close.mp3')
			  }else if (err.message='商品已经入过库了'){
					 this.pay('/static/mp3/ruku_chongfuruku.mp3')
			  }else{
				 _this.pay('/static/music/error.mp3')
			  }
		  }else{
			  _this.pay('/static/music/error.mp3')
		  }
		  console.log(err)
		})
      } else {
        // this.out()
		this.scanOder['driver_id'] = this.driverUser['driver_id']
        request.out({ ...this.scanOder }).then(response => {
          this.pay('/static/music/success.mp3')
          const { data } = response
          this.order = (data.order && data.order) || {}
          this.success_text = data.message || ''
          this.allStatus = data.status || 0
          uni.showToast({
            title: this.success_text,
            duration: 800,
            icon: 'none',
          })
        }).catch(err => {
			 if (err.message) {
				 if (err.message=='线路不对') {
					 this.pay('/static/mp3/out_xianlubudui.mp3')
				 }else{
					  this.pay('/static/music/error.mp3')
				 }
			 }else{
				 this.pay('/static/music/error.mp3')
			 }
          
          console.log(err)
        })
      }
    },
	logout(){
		uni.setStorageSync('driver-user','');
		this.driverUser = '';
		uni.showToast({
		  title: '已退出',
		  duration: 800,
		  icon: 'none',
		})
	}
  },
  onShow: function() {
    // 创建播放实例
	this.driverUser = uni.getStorageSync('driver-user');
    this.innerAudio = uni.createInnerAudioContext()
    // console.log(this.innerAudio)
    // var _this = this
    uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
    uni.$on('scancodedate', data => {
      // console.log(data.code)
      // console.log('你想要的code：', data.code)
      /**
       * data.code
       * {"order_id":14,"order_sn":"2022022222165373913"}
       */
      this.scanOder = JSON.parse(data.code)
      if (this.scanOder && this.scanOder.order_id && this.scanOder.order_sn && this.scanOder.current) {
        // setTimeout(() => {
        //   this.submit()
        // }, 200)
        this.submit()
      } else {
        this.success_text = '操作失败'
        uni.showToast({
          title: this.success_text,
          duration: 800,
          icon: 'none',
        })
        this.pay('/static/music/error.mp3')
      }

      // setTimeout(() => {
      //   this.success_text = ''
      //   this.order = {}
      // }, 3000)

    })
  },
  onUnload() {
  // 移除监听事件
    uni.$off('scancodedate')
  },
  onHide() {
    // 切记, 多个调试时, 一定要关掉其它的
    uni.$off('scancodedate')
  },
}
/*
其他的页面引用方法：不需要再次引入scanCode因为其他的页面都是从首页跳转过来的，所以其他的页面需要
onUnload() {
// 移除监听事件
uni.$off('scancodedate')
}


onLoad() {
   var _this = this
   uni.$on('scancodedate',function(data){
        // _this 这里面的方法用这个 _this.code(data.code)
    console.log('你想要的code：', data.code)
   })
},
onUnload() {
   // 移除监听事件
   uni.$off('scancodedate')
}

作者：南苑bert
链接：https://www.jianshu.com/p/0b1c869919bf
来源：简书
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
*/
</script>

<style>
page {
  background: #f1f1f1;
}
.wrapper {
  background: url("/static/bg.png");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center top;
  padding-top: 100rpx;
}
.bg {
  background: url("/static/bg2.png");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center top;
}
.header {
  /*background: red;*/
  height: 200rpx;
  padding: 20rpx;
  display: flex;
}
.title {
  font-weight: 700;
  font-size: 32rpx;
}
.ops {
  margin-left: 30rpx;
  color: white;
  margin-top: 50rpx;
  letter-spacing: 5rpx;
  font-size: 40rpx;
}
.ops.color {
  color: black;
}
.menu {
  background: white;
  height: 180rpx;
  padding: 20rpx;
  margin: 40rpx;
  display: flex;
  justify-content: space-around;
}
.into, .out {
  display: flex;
  flex-direction: column;
}
.into image, .out image {
  width: 130rpx;
  height: 130rpx;
  display: block;
}
.into text, .out text {
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
}
.main {
  background: white;
  padding: 20rpx;
  margin: 40rpx;
  min-height: 600rpx;
}
.main view {
  height: 40rpx;
  line-height: 40rpx;
  overflow: hidden;
  background: #eee;
  margin-bottom: 10rpx;
  padding: 0 20rpx;
}
.main .item {
  background: #efefef;
}
</style>
